<?php
/*
Copyright (C) 2011  Benjamin Marchand

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
class UsersController extends AppController {
	var $name = "Users";
	var $view = 'Theme';
	
	var $helpers = array('Html','Javascript','Session','Js' => array('jquery'));
	var $components = array('RequestHandler','Auth','MathCaptcha','Spyc','Cookie','Session');
	var $uses = array('Setting','mctemplateplugin','User');
	
	function login()
	{
		$websitename = Configure::read('bukkitadmin.websitename');
		if (!empty($websitename))
		{
			$this->set('title_for_layout',$websitename);
		}
		else
		{
			$this->set('title_for_layout','Webukkit');
			$this->set('version',Configure::read('version'));
		}
	
	}
	
	function editprofile()
	{
		$this->autoLayout=FALSE;
		if (!empty($this->data))
		{
		$this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
			if ($this->data['User']['password']==$this->Auth->password($this->data['User']['password_confirm'])) {
			$this->User->id = $this->data['User']['id'];
			$this->User->save($this->data);
			$this->Session->setFlash('Profile saved!','flash_success');
			}
			else
			{
				$this->Session->setFlash('Passwords don\'t match!','flash_failure');
				return false;
			}
		}
		else
		{
			$this->data = $this->User->findByUsername($this->Auth->user('username'));
			$this->set('mathCaptcha', $this->MathCaptcha->generateEquation());
		}
	}
	
	function isAuthorized()
	{
		return TRUE;
	}
	
	function logout()
	{
		$this->Session->setFlash("You’ve successfully logged out.");
		$this->redirect($this->Auth->logout());
	}
	
	function afterFilter(){
		//retrieves the site-wide configurations from Configure::read($key) and puts it back into the db if new
		$this->Setting->writecfg();
	}
	
	function beforeFilter() {
		$this->Setting->getcfg();
		$this->Cookie->secure = true;
		/*$this->Cookie->time = '1 year'; // or '1 hour'
		$this->Cookie->key = 'rtumlsqqsfqsfd*$^651';*/
		$this->Auth->allow('login','register','kcaptcha','registersuccessful','check_username','setlang');
		$lang = $this->Cookie->read('langage');
		if (!is_null($lang))
			$this->setlang($lang);
	}
	
	function registersuccessful()
	{
		
	}
	
	function beforeRender()
	{
		$this->layout = 'install';
		$theme = Configure::read('bukkitadmin.theme');
		if (!empty($theme))
		{
			$this->theme = $theme;
		}

	}
	function register()
	{
		$usePermissionsPlugin = Configure::read('bukkitadmin.usePermissionsPlugin');
		$this->set('title_for_layout','User registration');
		if ( !empty( $this->data ) ){
			if ($this->data['User']['password']==$this->Auth->password($this->data['User']['password_confirm'])) {
				if ($this->MathCaptcha->validates($this->data['User']['security_code'])) {
					unset( $this->data['User']['security_code']);
					$this->data['User']['group'] = 2;
					if ($this->User->save($this->data)){
						if ($usePermissionsPlugin)
						{
							$this->_registerUserPP($this->data['User']['username'],$this->data['User']['password']);
						}
						$this->Session->setFlash('Successfully Registered!');
						$this->redirect(array('controller'=>'users','action'=>'registersuccessful'));
					}
					else
					{
						$this->set('errors',$this->User->invalidFields());
					}
				}
				else
				{
					$this->Session->setFlash('captcha verification failed');
				}
			}
			else
			{
				$this->Session->setFlash('password mismatch');
			}
		}
		$this->set('mathCaptcha', $this->MathCaptcha->generateEquation());
	}
	
	function _registerUserPP($username,$password)
	{
		$exist = FALSE;
		$passwordcheck = $this->User->findByUsername($username,array('fields'=>'password'));
		if ($passwordcheck['User']['password']==$password)
		{
			$ppdefaultgroup = Configure::read('bukkitadmin.ppdefaultgroup');
			$ppdefaultworld = Configure::read('bukkitadmin.ppdefaultworld');
			$path = Configure::read('bukkitadmin.MinecraftPath');
			$path .= DS.'plugins'.DS.'Permissions'.DS.$ppdefaultworld;
			//$data = $this->mctemplateplugin->findByName('Permissions');
			if ((!empty($ppdefaultgroup)) && (file_exists($path)))
			{
				// We check if the name already exist
				$config = $this->Spyc->YAMLLoad($path);
				foreach ($config['users'] as  $key => $value)
				{
					if ($key==$username)
					{
						$exist = TRUE;
						break;
					}
				}
				if (!$exist)
				{
					//$data = $this->Spyc->YAMLLoad($path.$data['mctemplateplugin']['config']);
					$config['users'][$username] = array('group'=>$ppdefaultgroup,'permissions'=>'');
					file_put_contents($path,$this->Spyc->dump($config));
				}
			}
		}
	}
	
	function check_username() {
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		if (!empty($this->data))
		{
			$u=$this->User->findByUsername($this->data);
			if (empty($u))
			{
				$messages[] = array('image'=>'check-success.png','message'=>'');
			}
			else
			{
				$messages[] = array('image'=>'clear_icon.png','message'=>'');
			}
		$this->set('messages',$messages);
		$this->render('/elements/message');
		}
	}
	
	function setlang($lang)
	{
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		if (empty($lang)) $lang = $this->params['form']['lang'];
		$this->Session->write('Config.language', $lang);
		// save the langage in cookie
		$this->Cookie->write('langage',$lang);
		//$this->redirect($this->referer());
	}
	
}
?>